import asyncio
import concurrent.futures
import logging
import os
import threading

from fastapi import APIRouter

from ..utils.response import APIResponse
from ..wrapper.demo_dll_wrapper import add_cpp, fibonacci_cpp  # 相对导入 DLL 包装器
from .items import router as items_router

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api", tags=["api"])
router.include_router(items_router, prefix="/items")


def fibonacci_py(n):
    if n == 1 or n == 2:
        return 1
    return fibonacci_py(n - 1) + fibonacci_py(n - 2)


def fibonacci_wrapper(n, f):
    thread_id = threading.get_ident()
    thread_name = threading.current_thread().name
    pid = os.getpid()
    print(f"当前进程 ID: {pid}, 线程 ID: {thread_id}, 名称: {thread_name}")
    return f(n)


executor = concurrent.futures.ProcessPoolExecutor(max_workers=10)


@router.get("/add")
async def add_numbers(a: int, b: int):
    def _add():
        thread_id = threading.get_ident()
        thread_name = threading.current_thread().name
        pid = os.getpid()
        print(f"当前进程 ID: {pid}, 线程 ID: {thread_id}, 名称: {thread_name}")
        return add_cpp(a, b)

    res = await asyncio.to_thread(_add)
    return APIResponse.ok(res)


@router.get("/fibonacci/py")
async def fibonacci_v1(n: int):
    res = await asyncio.to_thread(fibonacci_wrapper, n, fibonacci_py)
    return APIResponse.ok(res)


@router.get("/fibonacci/cpp")
async def fibonacci_v2(n: int):
    res = await asyncio.to_thread(fibonacci_wrapper, n, fibonacci_cpp)
    return APIResponse.ok(res)
